import { Message } from 'element-ui';
import store from '../store/index.js';
export const showTips = (type, msg) => {
    Message({
        message: msg,
        center: true,
        type: type
    });

}

export const local = {
    setItem(key, value) {
        if (typeof value !== 'string') {
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
    },
    getItem(key, type) {
        let val = localStorage.getItem(key);
        if (val) {
            if (type) {
                try {
                    val = JSON.parse(val);
                } catch (err) {
                    console.warn('json parse failed !');
                    val = null;
                }
                return val;
            } else {
                return val;
            }
        }
        return null;
    },
    removeItem(key) {
        localStorage.removeItem(key);
    },
    clear() {
        localStorage.clear();
    }
}

export const initStore = () => {
    store.commit('setToken', local.getItem('token'))
    store.commit('setUserInfo', local.getItem('user', true))
}

export const clearStorage = () => {
    store.commit('clearToken');
    sessionStorage.clear();
    const extendKeyMap = [
        'version'
    ]
    const obj = {};
    extendKeyMap.forEach(key => {
        obj[key] = localStorage.getItem(key);
    })
    localStorage.clear();
    Object.keys(obj).forEach(key => {
        if (obj[key]) {
            localStorage.setItem(key, obj[key]);
        }
    })
}